package com.iskny.framework.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

public class Menu extends Model<Menu> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7277899834043498918L;

	public static final String menuPageKey = "menupage";
	public final static Menu dao = new Menu();
	/**
	 * 根据id查找菜单
	 * @param id
	 * @return
	 */
	public List<Menu> findMenusByUserid(Long id) {
		String sql="select m.id,m.pid,m.name,m.opentype,s.title,s.url from t_menu m,t_siteurl s " +
				"where m.siteurl_id=s.id and m.state = 1 order by m.pid,m.sortnum";
		return dao.find(sql);
	}
	
	/**
	 * 根据id查找菜单
	 * @param id
	 * @return
	 */
	public List<MenuBean> findMenuBeansByUserid(Long id) {
		List<Menu> menus = findMenusByUserid(id);
		List<MenuBean> ret = new ArrayList<MenuBean>();
		Map<Long,MenuBean> parents = new HashMap<Long, MenuBean>();
		MenuBean temp = null;
		for(Menu m:menus){
			temp = new MenuBean(m);
			Long pid = temp.pid;
			if(pid.equals(-1L)){
				parents.put(temp.id, temp);
				ret.add(temp);
			}else{
				MenuBean p = parents.get(pid);
				if(p!=null){
					p.addChild(temp);
				}
			}
		}
		return ret;
	}

	public MyPage pageMenu(int pageNumber, int pageSize) {
		Page<Menu> ret = super.paginateByCache(menuPageKey, pageNumber+"_"+pageSize, 
				pageNumber, pageSize, "select m.*,s.url", //sortnum,name,state,createtime,url
				"from t_menu m,t_siteurl s where m.siteurl_id=s.id order by m.sortnum");
		return new MyPage(ret);
	}
	
}
